package com.joker.md5p;

import com.joker.myrealm.CumstomRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.Subject;

/**
 * 在这里我们使用 自定义的Realm
 */
public class TestMd5AuthorRealm {
    public static void main(String[] args) {

        DefaultSecurityManager securityManager=new DefaultSecurityManager();
        CumstomMd5Realm cumstomMd5Realm=new CumstomMd5Realm();
        // 设置匹配策略,
        HashedCredentialsMatcher hashedCredentialsMatcher=new HashedCredentialsMatcher();
        //设置Md5 加密
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        // 设置hash 散列度
        hashedCredentialsMatcher.setHashIterations(1024);
        cumstomMd5Realm.setCredentialsMatcher(hashedCredentialsMatcher);
        // 2. 给安全管理器设置Realm
        securityManager.setRealm(cumstomMd5Realm);

        // 给SecurityUtils 给全局安全工具类 设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);

        //  关键对象 Subject 主体
        Subject subject=SecurityUtils.getSubject();

        // 创建令牌
        UsernamePasswordToken token=new UsernamePasswordToken("joker","123456");

        try {
            // 如果输入的 token 是错误的信息，会报错
            System.out.println("自定义认证状态"+subject.isAuthenticated());
            subject.login(token);
            System.out.println("自定义认证状态"+subject.isAuthenticated());
            Realm realm;
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
